import path from 'path'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import IconsResolver from 'unplugin-icons/resolver'
import Icons from 'unplugin-icons/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Unocss from 'unocss/vite'
import { createHtmlPlugin } from 'vite-plugin-html'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'

const getViteEnv = (mode: any, target: any) => {
  return loadEnv(mode, 'env/')[target]
}

export default defineConfig(({ command, mode }) => {
  console.log('start', command, mode)
  let cfg = {
    resolve: {
      alias: {
        '~': path.resolve(__dirname, 'src/')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler',
          additionalData: `@use "~/styles/element/index.scss" as *;`
        }
      }
    },
    plugins: [
      vue(),
      createHtmlPlugin({
        inject: {
          data: {
            logo: getViteEnv(mode, 'VITE_FAV'),
            title: getViteEnv(mode, 'VITE_NAME')
          }
        }
      }),
      AutoImport({
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            prefix: 'Icon'
          })
        ],
        imports: [
          'vue',
          'vue-router',
          'vue-i18n',
          {
            '~/api': ['apis'],
            '~/utils/cache': ['cache'],
            '~/store/app': ['useAppStore'],
            '~/store/order': ['useOrderStore'],
            '~/utils/http': ['http', 'request'],
            '~/utils/util': [
              'hasAuth',
              'getDate',
              'showSugar',
              'showCold',
              'showName',
              'showPayWay',
              'showAgentType',
              'showAgentWay',
              'showChargeWay'
            ],
            '~/plugins/list': ['useList'],
            '~/plugins/dd': ['useDD'],
            '~/plugins/form': ['useRuleForm']
          }
        ],
        dts: 'src/dts/auto-import.d.ts',
        vueTemplate: true
      }),
      Components({
        extensions: ['vue'],
        resolvers: [
          IconsResolver({
            enabledCollections: ['ep']
          }),
          ElementPlusResolver({ importStyle: 'sass' })
        ],
        dts: 'src/dts/auto-components.d.ts'
      }),
      Icons({
        autoInstall: true
      }),
      Unocss(),
      VueSetupExtend()
    ],
    base: '/employee/',
    envDir: 'env/',
    server: { host: '0.0.0.0', port: 5174 }
  }

  return cfg
})
